// 导入
import { requestData } from '../../config/requestData.js'
import { videoUrl, groupUrl } from '../../config/api.js'
// let videoInstace = ''
Page({
  data: {
    currentIndex: '', // 当前索引
    navList: [], // 导航栏数据
    groupList: [], // 视频数据
    videoId: '', // id
    duration: 0, // 总计时长
    currentTime: 0, // 当前事件
    countArr: [], //记录暂停时间
    isTriggered: false, //下拉
  },
  onLoad() {
    this.loadingNavData()
  },
  // 方法
  handleRefresh () {
    wx.startPullDownRefresh(this.data.currentIndex) 
    this.setData({
      isTriggered: false
    })
  },
  handleUpdateTime(e) {
    const { id } = e.currentTarget.dataset
    const { currentTime } = e.detail
    let { countArr } = this.data
    let countObj = {
      id,
      currentTime
    }
    // 判断里面有没有数据
    let item = countArr.find(el => el.id === countObj.id)
    if (item) {
        item.currentTime = currentTime
    } else {
      countArr.push(countObj)
    }
    this.setData({
      countArr
    })
  },
  handleEnd (e) {
    const { id }= e.currentTarget.dataset
    const { countArr } = this.data
    let index = countArr.findIndex(el => el.id === id)
    countArr.splice(index, 1)
    this.setData({
      countArr
    })
    // this.videoInstace.stop()
  },
  handlePlay (e) {
    const id = e.currentTarget.dataset.id
    this.setData({
      videoId: id
    })
    const { countArr } = this.data
    this.videoInstace = wx.createVideoContext(id)
    const item = countArr.find(el => el.id === id)
    if(item) {
        this.videoInstace.seek(item.currentTime)
    }
    this.videoInstace.play()
  },
  goSearch () {
    wx.navigateTo({
      url: '/pages/search/search',
    })
  },
  handleNav (e) {
    const index = e.currentTarget.dataset.id
    this.setData({
      currentIndex: index
    })
    wx.showLoading({
      title: '加载中....',
    })
    this.loadingGroupData(this.data.currentIndex)
  },
  handleShare () {},
  // 加载方式
  async loadingNavData () {
    const options = {
      url: videoUrl
    }
    const res = await requestData(options)
    const { code, data } = res
    if (code === 200) {
      this.setData({
        navList: data,
        currentIndex: data[0].id
      })
      this.loadingGroupData(this.data.currentIndex)
    }
  },
  // 内容下的数据
  async loadingGroupData (id) {
    if(!id) return
    const options = {
      url: groupUrl,
      data: {
        id
      }
    }
    const res = await requestData(options)
    const { code, datas } = res
    if (code === 200) {
      wx.hideLoading()
      this.setData({
        groupList: datas,
        isTriggered: false
      })
      
    }
  },
  // 页面事件
  onShareAppMessage(res) {
    // console.log(res)
  },
  onPullDownRefresh () {
    this.loadingGroupData(this.data.currentIndex)
  }
})
